package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.TMessageBo;
import com.ruoyi.system.domain.vo.TMessageVo;
import com.ruoyi.system.domain.TMessage;
import com.ruoyi.system.mapper.TMessageMapper;
import com.ruoyi.system.service.ITMessageService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 留言Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-01
 */
@RequiredArgsConstructor
@Service
public class TMessageServiceImpl implements ITMessageService {

    private final TMessageMapper baseMapper;

    /**
     * 查询留言
     */
    @Override
    public TMessageVo queryById(String pkid){
        return baseMapper.selectVoById(pkid);
    }

    /**
     * 查询留言列表
     */
    @Override
    public TableDataInfo<TMessageVo> queryPageList(TMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TMessage> lqw = buildQueryWrapper(bo);
        Page<TMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询留言列表
     */
    @Override
    public List<TMessageVo> queryList(TMessageBo bo) {
        LambdaQueryWrapper<TMessage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TMessage> buildQueryWrapper(TMessageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TMessage> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), TMessage::getContent, bo.getContent());
        return lqw;
    }

    /**
     * 新增留言
     */
    @Override
    public Boolean insertByBo(TMessageBo bo) {
        TMessage add = BeanUtil.toBean(bo, TMessage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPkid(add.getPkid());
        }
        return flag;
    }

    /**
     * 修改留言
     */
    @Override
    public Boolean updateByBo(TMessageBo bo) {
        TMessage update = BeanUtil.toBean(bo, TMessage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TMessage entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除留言
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
